<?php
namespace app\home\controller;

use app\common\model\UserWalletDynamic;
use app\common\model\UserWalletDynamicLog;

use app\common\component\user\UserService;
use app\common\component\user_wallet_dynamic\UserWalletDynamicService;

class WithdrawDynamic extends ControllerBase {
	public function _initialize() {
		$this -> checkLogin();
	}

	public function index() {
		(new UserWalletDynamicService()) -> rewardOverTime();
		
		$userId = \think\Session::get('user_id');
		$this -> view -> assign('userWalletDynamics', UserWalletDynamic::alias('u_w_d')
			-> join('league_user u', 'u_w_d.from_user_id = u.user_id')
			-> field(
				'u_w_d.user_wallet_dynamic_id, u_w_d.user_id, u_w_d.from_user_id, u_w_d.type, u_w_d.status, u_w_d.price, u_w_d.remaining_price, u_w_d.create_time, u_w_d.over_time, ' .
				'u.username'
			)
			-> where('u_w_d.user_id', $userId) -> order('u_w_d.status ASC, u_w_d.user_wallet_dynamic_id DESC')
			-> paginate(10, true));

		$sumUserWalletDynamicPrice = UserWalletDynamic::where('user_id', $userId) -> where('status', 0) -> sum('remaining_price');
		$this -> view -> assign('sumUserWalletDynamicPrice', $sumUserWalletDynamicPrice);

        return $this -> view -> fetch();
	}

	public function withdraw() {
		$sumUserWalletDynamicPrice = UserWalletDynamic::where('user_id', \think\Session::get('user_id')) -> where('status', 0) -> sum('remaining_price');
		$this -> view -> assign('sumUserWalletDynamicPrice', $sumUserWalletDynamicPrice);

		$resultUser = (new UserService) -> getUser();
    	$this -> view -> assign('user', $resultUser['data']['user']);

		return $this -> view -> fetch();
	}

	public function handleWithdraw() {
		$post = $this -> request -> post();
		
		$DYNAMIC_REWARD_MULTIPLE = getParam('DYNAMIC_REWARD_MULTIPLE');
		if(($post['price'] % $DYNAMIC_REWARD_MULTIPLE) != 0) {
    		echo '<meta charset="utf-8"><script>alert("必须要以' . $DYNAMIC_REWARD_MULTIPLE . '倍起提!");window.history.go(-1);</script>';exit;
    	}

		$resultCheckPayPassword = (new UserService()) -> checkPayPassword($post['pay_password']);
    	if($resultCheckPayPassword['code'] !== 0) {
    		echo '<meta charset="utf-8"><script>alert("' . $resultCheckPayPassword['message'] . '!");window.history.go(-1);</script>';exit;
    	}

		$userId = \think\Session::get('user_id');
		$sumUserWalletDynamicPrice = UserWalletDynamic::where('user_id', $userId) -> where('status', 0) -> sum('remaining_price');
		if($sumUserWalletDynamicPrice < $post['price']) {
    		echo '<meta charset="utf-8"><script>alert("您的剩余金额不足!");window.history.go(-1);</script>';exit;
    	}

		$selectUserWalletDynamic = UserWalletDynamic::where('status = 0 AND user_id = ' . $userId) -> order('over_time ASC') -> select();
		\think\Db::startTrans();
		try {
			$UserWalletDynamicLog = new UserWalletDynamicLog([
				'user_id' => $userId,
				'type' => 2,
				'price' => $post['price'],
				'create_time' => time(),
				'remark' => '动态提现',
				'is_state' => 0
			]);
			if(!$UserWalletDynamicLog -> save()) {
				throw new \Exception('动态提现失败');
			}

			foreach($selectUserWalletDynamic as $UserWalletDynamic) {
				if($post['price'] <= 0) {
					break;
				}

				if($post['price'] >= $UserWalletDynamic -> remaining_price) {
					$post['price'] -= $UserWalletDynamic -> remaining_price;

					$UserWalletDynamic -> remaining_price = 0;
					$UserWalletDynamic -> status = 9;
				} else {
					$UserWalletDynamic -> remaining_price -= $post['price'];
					$post['price'] = 0;
				}

				if(!$UserWalletDynamic -> save()) {
					throw new \Exception('动态提现失败');
				}
			}
			\think\Db::commit();
		} catch(\Exception $e) {
			\think\Db::rollback();

			echo '<meta charset="utf-8"><script>alert("' . $e -> getMessage() . '!");window.history.go(-1);</script>';exit;
		}
		echo '<meta charset="utf-8"><script>alert("动态提现成功!");window.location.href="/withdraw/dynamic";</script>';exit;

	}
}
?>